import React from 'react';
import { createModalContainer } from '@/components/changeModal';
import {Button, message, Form, Alert, Row,Col,Radio,Select, Input, Cascader, Spin} from 'antd';
import { connect } from 'dva';
import styles from './index.less';
import {abs} from '@/utils/utils';
import InputPrices from '@/components/plugins/InputPrices';
import InputText from '@/components/Input/index';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
@Form.create()
class CancelAndAddressComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            price: props.param.RefundFee,
            addressList: [],
            addressList2: [],
            choiceItem: [],
            radioValue: 1,
            AddrId: '',
            loading: true,
        }
    }

    componentDidMount() {
        this.getStoreAddressListWithPage();
        this.getBaseAddress();
        window.Isoption = true;
    }

    componentWillMount() {
        window.Isoption = false;
      }


    // 取消
    handleCancel =() => {
        this.props.cancel();
    }

    onPriceChange = value => {
        this.setState({
          price: value,
        });
      };

    handleSubmit = e => {
        e.preventDefault();
        const { dispatch } = this.props;
        const {price, radioValue, AddrId} = this.state;
        this.props.form.validateFields((err, values) => {
            if(!err) {
                if(radioValue ===1) { //默认地址
                    dispatch({
                        type: 'orderRight/AgreeReturnGoods',
                        payload: {
                            Id: this.props.param.Id/1,
                            AddrId: AddrId/1,
                        },
                        callBack: {
                            success: res => {
                                if(res.Code===0) {
                                    message.success('发送成功');
                                    this.props.ok();
                                }
                            },
                            error: res => {
                                message.error(res.Msg)
                            }
                        }
                    })
                }
                if(radioValue===2) { //新增地址
                    dispatch({
                        type: 'orderRight/AgreeReturnAddr',
                        payload: {
                            Id: this.props.param.Id/1,
                            ContractName: values.name,
                            ContractPhone: values.phone,
                            ProvId: values.area[0],
                            ProvName: this.state.choiceItem[0].label,
                            CityId: values.area[1],
                            CityName: this.state.choiceItem[1].label,
                            DistrictId: values.area[2]?values.area[2]:values.area[1],
                            DistrictName: this.state.choiceItem[2]&&this.state.choiceItem[2].label?
                                  this.state.choiceItem[2].label:this.state.choiceItem[1].label,
                            AddressDetail: values.detail,
                        },
                        callBack: {
                            success: res => {
                                if(res.Code===0) {
                                    message.success('发送成功');
                                    this.props.ok();
                                }
                            }
                        }
                    })
                }
            }
        })
    }

    getStoreAddressListWithPage =() => {
        const { dispatch } = this.props;
        dispatch({
            type: 'address/GetStoreAddressListWithPage',
            payload: {
                PageIndex: 1,
                PageSize: 100,
            },
            callBack: {
                success: res => {
                    if(res.Code ===0) {
                        this.setState({
                            loading: false,
                            addressList: res.Data.DataList.length> 0?res.Data.DataList: [],
                            AddrId: res.Data.DataList.length> 0?
                            res.Data.DataList.filter(item => item.IsDefaultReceiving)[0].Id: ''
                        })
                    }
                }
            }
        })
    }

    addressTransform = (arr,arr2,parentIndex,childIndex) =>{
        let newArr=arr2||[];
        if(arr){
            for(let i=0;i<arr.length;i++){
                let item=arr[i];
                newArr.push({
                    value:item.Id,
                    label:item.Name,
                    children:[]
                });
                if(item.HasChild){
                    for(let j=0;j<item.Child.length;j++){
                        let item2=arr[i].Child[j];
                        newArr[i].children.push({
                            value:item2.Id,
                            label:item2.Name,
                            children:[]
                        })
                        if(item2.HasChild){
                            for(let k=0;k<item2.Child.length;k++){
                                let item3=arr[i].Child[j].Child[k];
                                newArr[i].children[j].children.push({
                                    value:item3.Id,
                                    label:item3.Name,
                                });
                            }
                        }
                    }
                }
            }
        }
        return newArr;
    }

    onChangeCascader =(value, select) => {
          this.setState({
              choiceItem: select
          })
      }

    // 获取地址
    getBaseAddress =() => {
        const { dispatch } = this.props;
        dispatch({
            type: 'address/GetBaseAddress',
            callBack: {
                success: res => {
                    if(res.Code ===0) {
                        this.setState({
                            addressList2: res.Data
                        })
                    }
                },
                error: res => {
                    message.error(res.Msg);
                }
            }
        })
    }

    // 跳地址库
    clickAddressList =()=> {
        window.open(`/#/${window.storeId}/store/address`);
    }

    changeRadio=(e)=> {
        this.setState({
            radioValue: e.target.value,
        });
    }

    changeSelect =(e) => {
        this.setState({
            AddrId: e.key
        })
    }

    render() {
        const {getFieldDecorator} = this.props.form;
        const max = this.props.param.RefundFeeMax;
        const {addressList, radioValue, addressList2, loading} = this.state;
        const defaultList = addressList.length> 0 ?addressList.filter(item => item.IsDefaultReceiving):[];
        const defaultValue1 = defaultList[0]?`【${defaultList[0].ContractName}收】${defaultList[0].ProvName}${defaultList[0].CityName}
        ${defaultList[0].DistrictName}${defaultList[0].AddressDetail}`:'';
        const defaultValue2 = defaultList[0]?defaultList[0].Id:'';
        const {loading1, loading2} = this.props;
        const formItemLayout = {
            labelCol: {
                span: 5,
              },
              wrapperCol: {
                span: 19,
              },
          }
          const formItemLayout1 = {
            labelCol: {span: 5},
            wrapperCol: { span: 14 },
        };
        const formItemLayout2 = {
            labelCol: {span: 5},
            wrapperCol: { span: 18 },
        };
          const radioStyle = {
            display: 'block',
            height: '40px',
            lineHeight: '40px',
          };
          let options=this.addressTransform(addressList2,[],0);
        return (
            <Form onSubmit={this.handleSubmit}>
               <Spin spinning={loading}>
                <Alert
                    message={this.props.param.type?
                        '该笔订单通过“货到付款/线下付款”付款，需你同意退款申请，买家才能退货给你；买家退货后，请您自行与买家协商退款方式，系统只能标记退款记录':
                        "该笔订单通过“微信支付”付款，需你同意退款申请，买家才能退货给你；买家退货后你需再次确认收货后，退款将自动原路退回至买家付款账户"
                    }
                    type="warning"
                    showIcon
                    style={{margin: 24}}
                />
                <FormItem {...formItemLayout} label="处理方式">退货退款</FormItem>
                {/* <FormItem
                    {...formItemLayout}
                    label="退款金额"
                    extra={
                        <span>最多可退￥{abs(max, 2)}</span>
                    }
                >
                    {getFieldDecorator('Fee',{
                        initialValue: this.state.price,
                        rules: [{required: true, message: '此项为必选项'}]
                    })(
                        <InputPrices
                            min={0.01}
                            max={max}
                            onChange={this.onPriceChange}
                            style={{width: 144}}
                            setValue={this.state.price}
                      />
                    )}
                </FormItem> */}
                <FormItem
                    {...formItemLayout}
                    label="退款金额"
                >
                    ￥{abs(this.props.param.RefundFee,2)}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="退货地址"
                >
                    {getFieldDecorator('address',{
                        initialValue: 1,
                        rules: [{required: false, message: '此项为必选项'}]
                    })(
                        <div>
                            <div><a onClick={this.clickAddressList}>管理地址</a></div>
                            <RadioGroup onChange={this.changeRadio} value={radioValue}>
                                {addressList.length> 0 && (
                                    <Radio value={1} style={radioStyle}>
                                        <Select
                                            style={{maxWidth: 350}}
                                            defaultValue={{key: defaultValue2}}
                                            labelInValue
                                            onChange = {this.changeSelect}
                                        >
                                            {addressList.map((item, index) => {
                                                return (
                                                    <Option value={item.Id} key={index}>
                                                    【{item.ContractName}收】{item.ProvName}{item.CityName}{item.DistrictName}{item.AddressDetail}
                                                    </Option>
                                                )
                                            })}
                                        </Select>
                                    </Radio>
                                )}
                                <Radio value={2} style={radioStyle}>使用新地址</Radio>
                            </RadioGroup>                          
                        </div>                       
                    )}
                </FormItem>
                {radioValue===2 &&(<Row>
                    <Col span={17} push={5} className={styles.colItem}>
                        <Form.Item
                            label="联系人"
                            {...formItemLayout1}
                        >{getFieldDecorator('name', {
                            rules: [
                                {required: radioValue===2?true:false, message: '联系人必须填写'},
                        ]
                        })(
                        <InputText name="name" onChange={this.onTextChange}  showtotal maxLength={10} />
                        )}
                        </Form.Item>
                        <Form.Item
                            label="联系电话"
                            {...formItemLayout1}
                        >{getFieldDecorator('phone', {
                            rules: [
                                {required: radioValue===2?true:false, message: '联系电话必须填写'},
                                {pattern: /0?(13|14|15|17|18|19)[0-9]{9}/, message:'请填写正确电话号码'}
                        ]
                        })(
                            <Input />
                        )}
                        </Form.Item>
                        <Form.Item
                            label="地区"
                            {...formItemLayout2}
                        >{getFieldDecorator('area', {
                            rules: [
                                {required: radioValue===2?true:false, message: '地区必须填写'}
                        ]
                        })(
                            <Cascader options={options} onChange={this.onChangeCascader} placeholder="" />
                        )}
                        </Form.Item>
                        <Form.Item
                            label="详细地址"
                            {...formItemLayout2}
                        >{getFieldDecorator('detail', {
                            rules: [
                                {required: radioValue===2?true:false, message: '详细地址必须填写'}
                        ]
                        })(
                        <InputText name="detail" onChange={this.onDetailChange}  showtotal maxLength={60} />
                        )}
                        </Form.Item>
                    </Col>
                </Row>)}
            
                <FormItem className="xkd-model-footBtn">
                    <Button
                        type="primary"
                        htmlType="submit"
                        loading={loading1 || loading2}
                    >
                        同意退货，发送退货地址
                    </Button>
                </FormItem>
                </Spin>
            </Form>
        )
    }
}

const CancelAndAddress = createModalContainer(
    connect(({orderRight, global, loading}) =>({
    orderRight,
    loading1: loading.effects['orderRight/AgreeReturnAddr'],
    loading2: loading.effects['orderRight/AgreeReturnGoods'],
    }))(CancelAndAddressComponent),
    true,
    true
);

export default CancelAndAddress;